from sqlalchemy.orm import Session
from sqlalchemy import or_
from app.models.user import User, UserFollow
from app.schemas.user import UserCreate, UserUpdate
from app.core.security import get_password_hash
from typing import List, Optional

def get_user(db: Session, user_id: int) -> Optional[User]:
    """通过ID获取用户"""
    return db.query(User).filter(User.id == user_id).first()

def get_user_by_username(db: Session, username: str) -> Optional[User]:
    """通过用户名获取用户"""
    return db.query(User).filter(User.username == username).first()

def get_user_by_email(db: Session, email: str) -> Optional[User]:
    """通过邮箱获取用户"""
    return db.query(User).filter(User.email == email).first()

def get_users(db: Session, skip: int = 0, limit: int = 100, search: Optional[str] = None, status: Optional[str] = None) -> List[User]:
    """
    获取用户列表
    可以通过搜索条件和状态过滤
    """
    query = db.query(User)
    
    # 应用搜索过滤
    if search:
        search_term = f"%{search}%"
        query = query.filter(
            or_(
                User.username.like(search_term),
                User.full_name.like(search_term),
                User.email.like(search_term)
            )
        )
    
    # 应用状态过滤
    if status:
        query = query.filter(User.status == status)
    
    # 返回分页结果
    return query.offset(skip).limit(limit).all()

def create_user(db: Session, user: UserCreate) -> User:
    """创建用户"""
    # 创建用户对象
    db_user = User(
        username=user.username,
        email=user.email,
        hashed_password=get_password_hash(user.password),
        full_name=user.full_name,
        avatar=user.avatar,
        bio=user.bio,
        status=user.status,
    )
    # 添加到数据库
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def update_user(db: Session, user_id: int, user_update: UserUpdate) -> Optional[User]:
    """更新用户信息"""
    # 获取用户
    db_user = get_user(db, user_id)
    if not db_user:
        return None
    
    # 更新用户数据
    update_data = user_update.dict(exclude_unset=True)
    
    # 如果有密码，需要处理成哈希密码
    if "password" in update_data:
        update_data["hashed_password"] = get_password_hash(update_data.pop("password"))
    
    # 更新数据
    for key, value in update_data.items():
        setattr(db_user, key, value)
    
    # 提交更改
    db.commit()
    db.refresh(db_user)
    return db_user

def update_user_status(db: Session, user_id: int, status: str) -> Optional[User]:
    """
    更新用户状态
    状态可以是: active, disabled, banned
    """
    db_user = get_user(db, user_id)
    if not db_user:
        return None
    
    # 更新状态
    db_user.status = status
    
    # 如果状态是 disabled 或 banned，同时设置 is_active 为 False
    if status in ["disabled", "banned"]:
        db_user.is_active = False
    else:
        db_user.is_active = True
    
    # 提交更改
    db.commit()
    db.refresh(db_user)
    return db_user

def delete_user(db: Session, user_id: int) -> bool:
    """删除用户（标记为非活跃）"""
    db_user = get_user(db, user_id)
    if not db_user:
        return False
    
    # 标记为非活跃而不是真正删除
    db_user.is_active = False
    db_user.status = "disabled"
    db.commit()
    return True

def follow_user(db: Session, follower_id: int, followed_id: int) -> Optional[UserFollow]:
    """关注用户"""
    # 检查两个用户是否存在
    follower = get_user(db, follower_id)
    followed = get_user(db, followed_id)
    
    if not follower or not followed:
        return None
    
    # 检查是否已经关注
    existing_follow = db.query(UserFollow).filter(
        UserFollow.follower_id == follower_id,
        UserFollow.followed_id == followed_id
    ).first()
    
    if existing_follow:
        return existing_follow
    
    # 创建关注关系
    db_follow = UserFollow(follower_id=follower_id, followed_id=followed_id)
    db.add(db_follow)
    db.commit()
    db.refresh(db_follow)
    return db_follow

def unfollow_user(db: Session, follower_id: int, followed_id: int) -> bool:
    """取消关注用户"""
    # 查找关注关系
    db_follow = db.query(UserFollow).filter(
        UserFollow.follower_id == follower_id,
        UserFollow.followed_id == followed_id
    ).first()
    
    if not db_follow:
        return False
    
    # 删除关注关系
    db.delete(db_follow)
    db.commit()
    return True

def get_followers(db: Session, user_id: int, skip: int = 0, limit: int = 100) -> List[User]:
    """获取用户的关注者列表"""
    return db.query(User).join(
        UserFollow, UserFollow.follower_id == User.id
    ).filter(
        UserFollow.followed_id == user_id
    ).offset(skip).limit(limit).all()

def get_following(db: Session, user_id: int, skip: int = 0, limit: int = 100) -> List[User]:
    """获取用户关注的用户列表"""
    return db.query(User).join(
        UserFollow, UserFollow.followed_id == User.id
    ).filter(
        UserFollow.follower_id == user_id
    ).offset(skip).limit(limit).all() 